package handler

import (
	"strconv"
	"net/http"
	"github.com/gin-gonic/gin"
	"../models"
)

func Ping(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
	})
}

func Hello(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"title": "gin-blog",
		"word": "hello, world!",
	})
}

func AllArticles(c *gin.Context) {
	articles, err := models.GetAllArticles()
	if err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return 
	}
	c.JSON(http.StatusOK, gin.H{
		"articles": articles,
	})
}

func Article(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	article, err := models.GetArticleById(id);
	if  err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return
	} 
	c.JSON(http.StatusOK,  gin.H{
		"article": article,
	})
}

func CreateArticle(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	var article models.Article
	article.Title = title
	article.Content = content
	if err := article.Create(); err != nil {
		c.AbortWithStatus((http.StatusInternalServerError))
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"article": article,
	})
}

func UpdateArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	article, err := models.GetArticleById(id)
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	title := c.DefaultQuery("title", "")
	content := c.DefaultQuery("content", "")
	if title != "" {
		article.Title = title
	}
	if content != "" {
		article.Content = content
	}
	if err := article.Update(); err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"article": article,
	})
}

func DeleteArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	article := models.Article{ID: id}
	if err := article.Delete(); err != nil {
		c.AbortWithError(http.StatusNotFound, err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status": 1,
	})
}

func RemoveAllArticles(c *gin.Context) {
	models.RemoveAllArticles()
	c.JSON(http.StatusOK, gin.H{
		"status": 1,
	})
}